import { useMutation } from '@tanstack/react-query';
import { message, Modal } from 'antd';
import React from 'react';

import api from '@/apis/api';
import localINFO from '@/utils/localInfo';

interface LogoutModalProps {
  visible: boolean;
  setVisible: (visible: boolean) => void;
}

const LogoutModal: React.FC<LogoutModalProps> = ({ visible, setVisible }) => {
  // 退出登录接口方法
  const logout = useMutation({
    mutationFn: async () => api.Logout(),
    onSuccess: (res: any) => {
      if (res?.success) {
        // 成功提示
        message.open({
          key: 'logout',
          type: 'success',
          content: '退出登录成功',
        });
      } else {
        // 失败提示
        message.open({
          key: 'logout',
          type: 'error',
          content: `退出登录失败,${res?.message}`,
        });
      }
    },
    onError: () => {
      message.open({
        key: 'logout',
        type: 'error',
        content: '退出登录失败',
      });
    },
  });

  const handleOk = async () => {
    if (localINFO.getRoleId() === 2) {
      // 操作员退出登录
      setVisible(false);
      // 清除本地存储或其他与用户相关的信息
      localINFO.clear();
      window.location.href = '/login';
      return;
    }
    const res: any = await logout.mutateAsync();
    if (res?.success) {
      message.open({
        key: 'logout',
        type: 'success',
        content: '退出登录成功',
      });
      setVisible(false);
      // 清除本地存储或其他与用户相关的信息
      localINFO.clear();
      window.location.href = '/login';
    } else {
      // 失败提示
      message.open({
        key: 'logout',
        type: 'error',
        content: '退出登录失败',
      });
    }
  };

  const handleCancel = () => {
    setVisible(false);
  };

  return (
    <Modal
      title="退出登录"
      open={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      cancelText="取消"
      okText="确定"
    >
      <p style={{ marginLeft: 24 }}>您确定要退出登录吗？</p>
    </Modal>
  );
};

export default LogoutModal;
